import { mapGetters } from 'vuex'
import {
  getSceneStatus,
  handleSceneGroup,
  handleSceneItem,
  autoSwitchScene,
} from '@/utils/scene'

import { doubleClick } from '@/utils'

import { handleSystemMenu } from '@/utils/menu'
import autoSwitchSceneMixin from '@/mixins/switch-scene'

const MARGIN_WIDTH = 10
const GROUP_PADDING_WIDTH = 10
export default {
  mixins: [autoSwitchSceneMixin],
  data() {
    return {
      showScene: false,
      showSceneGroup: false,
      sceneId: null,
      sceneIndex: 0,
      sceneGroupId: null,
      sceneGroupIndex: 0,
      cacheScene: null,
      isUserClick: true,
      sceneWidthObj: {
        width: document.documentElement.clientWidth + 'px',
      },
      comsumerStyle: {},
      isCheckSceneIndex: true,
    }
  },
  mounted() {
    // 初始化场景状态
    this.$nextTick(() => {
      this.showScene = getSceneStatus()

      // 10s后开始自动切换，如果用户开启了该功能
      setTimeout(() => {
        this.handleRestartAutoSwitchScene()
      }, 10 * 1000)

      if (this.showScene) {
        setTimeout(() => {
          this.initListWidth()
          // 初始化第一个分组的第一个场景文字滚动（如果文字超出长度的话）
          this.checkScrollText(0)
        }, 200)
      }
      // 用户自定义样式
      if (window.$globalconfig.MODULES.SCENE_VIEW_TYPE) {
        this.comsumerStyle = {
          width: '100px',
          height: '80px',
          borderRadius: 0,
        }
      }
    })

    // 切换场景分组显示隐藏
    this.$vgo.on('scene:toggle', () => {
      this.showScene = !this.showScene

      if (this.showScene) {
        setTimeout(() => {
          this.initListWidth()
        }, 200)
      }
      // 当场景隐藏隐藏时候，触发显示后重新刷新scroll
      this.$vgo.emit('refresh:scroll')
    })

    // 热点/一键导览/小地图等热点触发场景切换
    this.$vgo.on('sync:scene', (sceneId, isUserClick) => {
      console.log('88--------------')
      console.log(sceneId)
      console.log(isUserClick)
      this.isUserClick = isUserClick
      this.beforeSwitchScene(sceneId)
    })

    // 付费后解锁场景
    this.paySuccess()
  },
  computed: {
    ...mapGetters([
      'panoInfo',
      'sceneGroup',
      'sceneList',
      'scenicSceneInfo',
      'themeId',
      'menuData',
      'hotspots',
    ]),
    getComsumerStyle() {
      return this.comsumerStyle
    },
    getSceneStatus() {
      return this.showScene
    },
    getThemeId() {
      if (this.themeId) return this.themeId
    },
    getSceneGroup() {
      if (this.sceneGroup && this.sceneGroup.length) {
        if (this.sceneGroup.length == 1 && this.sceneGroup[0].album == '默认') {
          this.showSceneGroup = false
        } else {
          this.showSceneGroup = true
        }
        return this.sceneGroup
      }
    },
    getWidth() {
      if (this.sceneGroup && this.sceneGroup.length) {
        if (this.sceneGroup.length == 1 && this.sceneGroup[0].album == '默认') {
          this.showSceneGroup = false
        } else {
          this.showSceneGroup = true
        }
        return (this.sceneGroup.length * 75)
      }
      return 500
    },
    getPcWidth() {
      if (this.sceneGroup && this.sceneGroup.length) {
        if (this.sceneGroup.length == 1 && this.sceneGroup[0].album == '默认') {
          this.showSceneGroup = false
        } else {
          this.showSceneGroup = true
        }
        return (this.sceneGroup.length * 90)
      }
      return 500
    },
    getSceneList() {
      if (this.panoInfo && this.panoInfo.templatetype == 12) {
        if (this.scenicSceneInfo && this.scenicSceneInfo.scene_spots_list && this.scenicSceneInfo.scene_spots_list.length > 0) {
          return this.scenicSceneInfo.scene_spots_list
        }
      } else {
        if (this.sceneList) {
          return this.sceneList
        }
      }
    },
    getStyle() {
      if (this.panoInfo && this.panoInfo.templatestyle && this.panoInfo.templatestyle != '') {
        return JSON.parse(this.panoInfo.templatestyle)
      }
    },
    getBottomMenuLenth() {
      if (this.menuData) {
        return this.menuData.bottommenu.length
      }
    },
    getSceneWidth() {
      if (this.sceneList && this.showScene) {
        return (this.sceneWidthObj.width =
          this.sceneList.length * (this.$refs.sceneItem[0].offsetWidth + 10) +
          'px')
      }
    },
  },
  watch: {
    sceneList(data) {
      this.initListWidth()
    },
    immediate: true,
  },
  methods: {
    initListWidth() {
      // 如果场景隐藏直接返回
      if (!this.showScene) return
      const vw = document.documentElement.clientWidth

      const getSceneWidth = () => {
        let sceneListDom = this.$refs.sceneListWrap
        let sceneItems = this.$refs.sceneItem
        if (sceneListDom && sceneItems) {
          let sceneItem = sceneItems[0]
          let sceneItemWidth = sceneItem.offsetWidth + MARGIN_WIDTH
          // 计算场景宽度
          let sceneWidth = sceneItemWidth * this.getSceneList.length

          // 如果场景宽度小于可视区的话则居中
          if (this.getThemeId != 11 && this.getThemeId != 12 && sceneWidth <= vw) {
            sceneListDom.style.width = vw + 'px'
            sceneListDom.style.textAlign = 'center'
          } else {
            sceneListDom.style.width = sceneWidth + MARGIN_WIDTH + 'px'
            sceneListDom.style.textAlign = 'left'
          }
          this.$refs.scrollSceneWrap.refresh()
        } else {
          setTimeout(getSceneWidth, 500)
        }
      }
      getSceneWidth()

      const initSceneIndex = () => {
        let sceneId = this.$route.query.scene_id
        if (this.isCheckSceneIndex && this.sceneGroup && sceneId) {
          this.isCheckSceneIndex = false
          this.sceneGroup.map((item, gidx) => {
            item.scenelist.map((it, i) => {
              if (it.scene_id == sceneId) {
                this.sceneGroupId = item.groupid
                this.sceneGroupIndex = gidx
                this.sceneIndex = i
                //handleSceneItem(it, this.sceneGroupId)
              }
            })
          })
        }
      }
      initSceneIndex()

      // 如果有分组
      if (!this.showSceneGroup) return
      const getGroupWidth = () => {
        let groupWrap = this.$refs.sceneGroupWrap
        // 没有值返回
        if (!groupWrap) return
        let groupChild = groupWrap.children
        let groutWidth = 0

        // 计算分组宽度
        for (let i = 0; i < this.getSceneGroup.length; i++) {
          groutWidth += groupChild[i].offsetWidth + 10
        }

        // 如果分组宽度小于可视区的话则居中
        if (this.getThemeId != 11 && groutWidth < vw) {
          groupWrap.style.width = vw + 'px'
          groupWrap.style.textAlign = 'center'
        } else {
          groupWrap.style.width = groutWidth + GROUP_PADDING_WIDTH + 'px'
          groupWrap.style.textAlign = 'left'
        }
        const groupScrollWrap = this.$refs.scrollGroupWrap
        if (groupScrollWrap) {
          groupScrollWrap.refresh()
        }
      }
      getGroupWidth()
    },
    beforeSwitchScene(sceneId) {
      if (this.sceneGroup) {
        this.sceneGroup.map((item, gidx) => {
          item.scenelist.map((it, i) => {
            if (it.scene_id == sceneId) {
              this.sceneGroupId = item.groupid
              this.sceneGroupIndex = gidx
              this.sceneIndex = i
              handleSceneItem(it, this.sceneGroupId)
            }
          })
        })
      }
    },
    // 分组切换
    handleGroupSwitch(groupId, index) {
      this.sceneGroupIndex = index
      this.sceneGroupId = groupId
      this.isUserClick = true
      handleSceneGroup(groupId)
      this.handleSceneSwitch(this.sceneList[0], 0, true)
    },
    // 场景切换
    handleSceneSwitch(item, index, isUserClick) {
      // console.log(item)
      // return
      this.sceneId = item.scene_id
      if (!this.sceneGroupId && this.getSceneGroup.length) {
        this.sceneGroupId = this.getSceneGroup[0].groupid
      }

      // 场景切换
      handleSceneItem(item, this.sceneGroupId)

      // 自动切换处理
      if (isUserClick) {
        autoSwitchScene(index, this.sceneGroupIndex)
      }

      // 清理掉其他场景滚动文字
      const { text } = this.$refs
      if (text) {
        for (let i = 0, len = text.length; i < len; i++) {
          text[i].classList.remove('move')
        }
      }

      // 场景标题超出宽度滚动
      this.checkScrollText(index)

      // 多屏互动
      this.$vgo.emit('socket:scene', item.scene_id)

      this.sceneIndex = index
    },
    // 场景标题滚动
    checkScrollText(index) {
      // 如果不是当前选中场景清除滚动
      if (this.sceneIndex != index) {
        this.cleanScrollText(index)
      }
      this.timer = setTimeout(() => {
        const { sceneItem, text } = this.$refs
        // console.log(sceneItem)
        // console.log(text)
        // console.log(index)
        if (text && text.length > index) {
          const textRef = text[index]

          // 如果文字长度未超出直接返回
          if (textRef.offsetWidth <= sceneItem[0].offsetWidth) return
          // 添加运动
          textRef.classList.add('move')
        }
      }, 100)
    },
    // 清除场景标题滚动
    cleanScrollText(index) {
      // 清除定时器
      clearTimeout(this.timer)
      if (this.sceneIndex != index) {
        const { text } = this.$refs
        if (text) {
          const textRef = text[index]
          // 移除样式
          if (textRef) {
            textRef.classList.remove('move')
          }
        }
      }
    },
    // 显示隐藏热点
    showHotspot() {
      console.log(this.hotspots)
      // if (this.hotspots && this.aerialSceneId) {
      //   if (this.hotspots[this.aerialSceneId].hotspotlist && this.hotspots[this.aerialSceneId].hotspotlist.length > 0) {
      //     hots = this.hotspots[this.aerialSceneId].hotspotlist
      //     hots.map(item => {
      //       this.$krp._krpano.set(`hotspot[hotspot_${item.hot_id}].visible`, true)
      //     })
      //   }
      // }
    },

    // 双击切换场景面板
    handleToggleScene() {
      handleSystemMenu({ type_id: 'scene' })
    },

    // 双击事件处理
    handleToggleTouch(e) {
      if (doubleClick(e)) {
        this.handleToggleScene()
      }
    },
    showSceneInfo(title, desc) {
      this.$vgo.emit('noticetip:show', { title: title, desc: desc, open: true })
    },
    // 付款成功
    paySuccess() {
      this.$vgo.on('update:scene', sceneId => {
        this.$store.dispatch('unlockScene', sceneId)
      })
    },
  },
}
